package logic

import (
	"context"
	"fmt"
	"house1/model/cache"
	"house1/model/mysql"
	"house1/pkg"

	"house1/houserpc/houserpc"
	"house1/houserpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterLogic) Register(in *houserpc.RegisterRequest) (*houserpc.RegisterResponse, error) {
	// todo: add your logic here and delete this line
	var finduser mysql.User
	mysql.DB.Debug().Where("phone=?", in.Phone).Find(&finduser)
	if finduser.ID != 0 {
		return nil, fmt.Errorf("用户存在,请前去登陆")
	}
	result, _ := cache.Rdb.Get(l.ctx, "Sendsms"+in.Phone).Result()
	if result != in.SendCode {
		return nil, fmt.Errorf("短信验证码验证失败,请重新输入")
	}

	user := mysql.User{
		Phone:    in.Phone,
		Password: pkg.Md5(in.Password),
	}
	mysql.DB.Debug().Create(&user)

	return &houserpc.RegisterResponse{}, nil
}
